package com.liyong.bos.service;

import com.liyong.bos.dao.BcRegionMapper;
import com.liyong.bos.domain.BcRegion;
import com.liyong.bos.domain.BcRegionExample;
import com.liyong.bos.utils.PinYin4jUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ApacheMoy on 2017/4/9.
 */
@Service
public class BcRegionServiceImpl implements BcRegionService {
    @Autowired
    private BcRegionMapper bcRegionMapper;

    /**
     * 导入数据
     * 每一行代表一个字符串数组，按需取出
     * 区域编号	省份	    城市	     区域	邮编
     * QY001	北京市	北京市	东城区	110101
     * 利用pinyin4j生成对应编码（code）
     * code编码需要去除城市末尾“市”字
     */
    public void bcRegionPush(List<String[]> list) {
        List<BcRegion> bcRegions = new ArrayList<BcRegion>();
        for (String[] strs : list) {
            BcRegion bcRegion = new BcRegion();
            bcRegion.setId(strs[0]);
            bcRegion.setProvince(strs[1]);
            bcRegion.setCity(strs[2]);
            bcRegion.setDistrict(strs[3]);
            bcRegion.setPostcode(strs[4]);
            //city转码工作
            String city = strs[2].substring(0, strs[2].length() - 1);
            String[] stringToPinyin = PinYin4jUtils.stringToPinyin(city);
            String citycode = StringUtils.join(stringToPinyin, "");
            bcRegion.setCitycode(citycode);
            //shortcode转码工作(province+city+district)
            String province  = strs[1].substring(0, strs[1].length() - 1);
            String district  = strs[3].substring(0, strs[3].length() - 1);
            String info = province + city + district;//河北石家庄长安
            String[] headByString = PinYin4jUtils.getHeadByString(info);
            String shortcode = StringUtils.join(headByString, "");
            bcRegion.setCitycode(citycode);
            bcRegion.setShortcode(shortcode);
            bcRegions.add(bcRegion);
        }
        for(BcRegion bcRegion:bcRegions){
            bcRegionMapper.insertSelective(bcRegion);
        }
    }

    /**
     * 导出数据
     * 若导出数据，则参数设置为空就行
     * 若要分页，则参数不可空
     */
    public List<BcRegion> bcRegionGet(int start, int pageSize) {
        BcRegionExample bcRegionExample = new BcRegionExample();
        bcRegionExample.setLimitStart((start - 1) * pageSize);
        bcRegionExample.setLimitEnd(pageSize);
        List<BcRegion> bcRegions = bcRegionMapper.selectByExample(bcRegionExample);
        return bcRegions;
    }

    public int countByPage() {
        BcRegionExample bcRegionExample = new BcRegionExample();
        return bcRegionMapper.countByExample(bcRegionExample);
    }
}
